package com.appspot.battlerafts.servlets.game;

import com.appspot.battlerafts.classes.Game;
import com.appspot.battlerafts.classes.User;
import com.appspot.battlerafts.enums.GameState;
import com.appspot.battlerafts.jsons.GameOverJSON;
import com.appspot.battlerafts.utils.PMF;
import com.google.gson.Gson;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import static com.appspot.battlerafts.utils.Util.returnError;
import static com.appspot.battlerafts.utils.Util.returnSuccess;

/**
 * Created with IntelliJ IDEA.
 * User: Tonis
 * Date: 03.04.12
 * Time: 0:39
 * To change this template use File | Settings | File Templates.
 */
public class GameOver extends HttpServlet {
    private static final Logger log = Logger.getLogger(GameOver.class.getName());
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Gson gson = new Gson();

        GameOverJSON gameOverJSON = gson.fromJson(request.getParameter("data"), GameOverJSON.class);
       log.info(request.getParameter("data"));
        log.info(gameOverJSON.toString());
        PersistenceManager pm = PMF.get().getPersistenceManager();
        Game game;
        try {
            game = pm.getObjectById(Game.class, gameOverJSON.gameID);
            game.setGameState(GameState.OVER);
            for (User u : gameOverJSON.finalStates){
                log.info(u.toString());
                log.setLevel(Level.INFO);
                try {
                    User u2 = pm.getObjectById(User.class, u.getUID());
                    u2.setScore(u2.getScore() + u.getScore());
                    u2.setNrOfPlayedGames(u2.getNrOfPlayedGames()+1);
                } catch (JDOObjectNotFoundException e){
                    returnError(response, "User with id " + u.getUID() + " was not found from database!");
                    return;
                }
            }
        } catch (JDOObjectNotFoundException e){
            returnError(response, "Game with id " + gameOverJSON.gameID + " has not been created yet!");
            return;
        } finally {
            pm.close();
        }

        returnSuccess(response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
